import App from './App'

import config from '@/common/static/data-config.js'
import areasNew from "@/util/areacommon.js";
import store from './store'
// import uView from './uni_modules/vk-uview-ui';
import uviewPlus from '@/uni_modules/uview-plus'

// #ifdef APP-HARMONY
// import {
//     checkPermission, requestPermissions
// } from '@/uni_modules/permission-handler-plus'

// const requestTrack=(callback)=> {
//     checkPermission('AppTrackingTransparency', (result) => {
//         console.log('main.js-AppTrackingTransparency',result)
//         if (result == "denied") {
//             requestPermissions({
//                 names: ['AppTrackingTransparency'],
//                 success: (result) => {
//                     console.log(1,result)
// 					callback();
//                 },
//                 fail:(error) => {
//                     console.log(2,error)
//                 }
//             })
//         }else{
// 			callback();
// 		}
//     })
// }
// #endif

var os = '';
var ver = '';

// 和设备相关，涉及个人隐私
var uuid = '';
// 和应用相关
var cid = ''
// #ifdef H5
var uuid = '3322B5D44B3234D891725C35513F49D7'
var cid = 'd0686d24d0ba28db9b4c684ef9405681';
// #endif

const dataFn = (app) => {

	//基础配置
	app.config.globalProperties.baseConfig = config;
	app.config.globalProperties.productionTip = false

	// ---------- 引入插件 ------------

	// 远程地区接口加载完毕
	app.config.globalProperties.$onLaunched = new Promise(resolve => {
		app.config.globalProperties.$isResolve = resolve
	})
	app.config.globalProperties.$userinfo = new Promise(resolve => {
		app.config.globalProperties.$userinfoisResolve = resolve
	})

	/**
	 * 当前用户登录信息
	 * 即登录接口返回的数据
	 */
	app.config.globalProperties.currUser = {
		logintype: 0, //0 验证码 1 用户名密码 (以后可以扩展其它,微信登录,QQ登录等!)
		islogin: false,
		token: '',
		user_id: 0,
		user_name: '游客',
		user_company: '',
		user_permission: 0
	};

	/**
	 * 当前用户权限信息
	 * User/login/UserLoginStateCheckHandler.ashx 接口返回的用户信息
	 */
	app.config.globalProperties.userInfo = {}

	/**
	 * 初始化参数
	 * 访问接口时使用，uni.request 用到
	 */
	app.config.globalProperties.initNewData = function() {
		return {
			guid: uuid,
			from: 4038,
			token: app.config.globalProperties.currUser.token,
			system: os, //手机系统 
			cid: cid,
			version: ver
		}
	};

	//登录
	app.config.globalProperties.doLogin = function() {
		uni.navigateTo({
			url: '/pages/user/login/login1'
		})
	}

	//退出 返回当前用户
	app.config.globalProperties.doLogout = function() {
		app.config.globalProperties.currUser = {
			logintype: 0, //0 验证码 1 用户名密码 (以后可以扩展其它,微信登录,QQ登录等!)
			islogin: false,
			token: '',
			user_id: 0,
			user_name: '',
			user_company: '',
			user_permission: 0
		};
		uni.setStorageSync("curruser", app.config.globalProperties.currUser)
	}

	//获取登录后的相关信息
	app.config.globalProperties.checkLogin = function(t) {
		let cUser = uni.getStorageSync("curruser");

		app.config.globalProperties.currUser = cUser;
		//User/login/UserLoginStateCheckHandler.ashx
		if (cUser.user_id > 0) {

			//访问接口获取验证码
			let data = app.config.globalProperties.initNewData();
			//位置类别
			data.location = 5118;
			// console.log(11,this)
			return uni.request({
				url: this.baseConfig.serverURL +
					'User/login/UserLoginStateCheckHandler.ashx', //检查更新的服务器地址
				data: data,
				method: "POST",
				header: {
					"content-type": "application/x-www-form-urlencoded" //"application/json"
				},
				success: (res) => {
					uni.hideToast();
					if (res.statusCode == 200) {
						if (res.data.ret) {
							uni.setStorageSync("isHuiyuan", res.data.other2.ispc)
							uni.setStorageSync('userInfo', res.data.other2)
							app.config.globalProperties.userInfo = res.data.other2;

							app.config.globalProperties.currUser = cUser;

						} else { //如果token失效，重置登录信息
							//console.log("客户失效：")
							app.config.globalProperties.doLogout();
							if (t == 1) {
								app.config.globalProperties.doLogin();
								return false;
							}
						}
						app.config.globalProperties.$userinfoisResolve();
					}
				},
				fail: (res) => {
					uni.showToast({
						title: '登录失败，可能已超时！',
						icon: "none"
					});
				}
			})
		} else {
			app.config.globalProperties.currUser = {
				logintype: 0, //0 验证码 1 用户名密码 (以后可以扩展其它,微信登录,QQ登录等!)
				islogin: false,
				token: '',
				user_id: 0,
				user_name: '',
				user_company: '',
				user_permission: 0
			};
			if (t == 1) {
				app.config.globalProperties.doLogin();
			}
			app.config.globalProperties.$userinfoisResolve();
		}

		return app.config.globalProperties.currUser;
	}

	// android, ios
	//#ifdef APP-PLUS
	const systemInfo = uni.getSystemInfoSync();
	const initfn = function() {
		// 用户同意隐私政策，可以调用限制API
		// plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
		// 	// 拿到的当前应用的版本，如果热更新，则是热更新的版本（应该是manifest中配置的）
		// 	// 注：并非apk/ipa(打包后，也可理解为自定义基座的版本号，即打包才可生效)的版本号
		// 	ver = wgtinfo.version;
		// 	// 如：5.3.0
		// 	// console.log('main.js ver',ver)
		// 	uni.setStorageSync('ver', ver)
		// })
		ver = systemInfo.appVersion
		uuid = systemInfo.deviceId;
		os = systemInfo.platform;
		

		/**
		 * 获取客户端信息
		 * 推送参数test:
			fpli iphone:d0686d24d0ba28db9b4c684ef9405681   
			oppo测试机: b5500364c92dc19f74a0e749b8d982ea
			hongmeng测试机：8e081d1ac037673df6378e74e52d35b7
			yahui:39586d7b7cbe2428dbad274f96f70ff1
			var clientid = 'd0686d24d0ba28db9b4c684ef9405681
		 */
		var info = plus.push.getClientInfo();
		cid = info.clientid;
		cid && uni.setStorageSync('cid', cid)
	}

	// 获取设备信息
	if (!systemInfo.platform === 'ios') {
		if (plus.runtime.isAgreePrivacy()) {
			initfn()
		}
	} else {
		initfn()
	}
	//#endif

	// #ifdef APP-HARMONY
	// const hongmengAuth=()=>{
		const systemInfo = uni.getSystemInfoSync();
		store.dispatch('updatesysteminfo', systemInfo)
		
		uuid = systemInfo.deviceId;
		os = systemInfo.platform;
		ver = systemInfo.appVersion
		// console.log('uuid,',uuid)
		uni.getPushClientId({
			success: (res) => {
				// console.log('cid', res.cid);
				cid=  res.cid
			},
			fail(err) {
				console.log(err)
			}
		})
	// }
	// requestTrack(hongmengAuth);
	
	// #endif
	
	uni.setStorageSync('ver', ver)
	
	console.log('11111----guid:', uuid)
	console.log('22222----cid:', cid)


	app.config.globalProperties.checkLogin();

	App.mpType = 'app'

	// const script = document.createElement('script');
	// script.src = 'https://static.bidcenter.com.cn/js/areacommon2024.js';
	// document.head.appendChild(script);

	// script.onload = () => {
	const areasCdn = Object.assign({}, areasNew)


	// 构建region数据结构
	for (var i in areasCdn) {
		// i = i.startsWith('v')?i.slice(1):i
		// 区域对象 qy,hb,db,hd,hz,hn,xn,xb（区域，华北，东北，华东，华中，华南，西南，西北）
		const arr = [];
		for (var m in areasCdn[i]) {

			arr.push({
				"k": m.startsWith('v') ? m.slice(1).padEnd(6, '0') : m,
				// 部分会匹配两个词：如 广西壮族自治区，会匹配壮族和自治区 两字词
				// "v": areasCdn[i][m].replace(/省|市|自治州|自治县|自治区|回族|壮族|维吾尔|特别行政区/g, ""),
				// "v": areasCdn[i][m],
				"v": areasCdn[i][m].replace(
					/省|市|县|自治区|回族|壮族|维吾尔|特别行政区|朝鲜族|布依族|苗族|侗族|彝族|哈尼族|傣族|白族|景颇族|傈僳族|藏族|自治州|蒙古族|蒙古自治州|哈萨克|土家族|羌族|柯尔克孜自治州|地区/gi,
					function(match, offset, string) {
						// console.log(match,offset,string)
						// 如果匹配到的是"省"，并且前面有"跨"字，则不替换
						if (match === "省" && string.slice(offset - 1, offset) === "跨") {
							// 返回原匹配的"省"
							return match;
						} else {
							return "";
						}
					}
				)
			})
		}
		if (i.startsWith('v')) {
			const keyval = i !== 'v0' ? i.slice(1).padEnd(6, '0') : i.slice(1)
			areasCdn[keyval] = arr
			delete areasCdn[i]
		} else {
			areasCdn[i] = arr;
		}
	}

	areasCdn['0'].unshift({
		'k': '',
		'v': '全国'
	})
	areasCdn["820000"] = [{
		"k": 821000,
		"v": "澳门"
	}];
	areasCdn["810000"] = [{
		"k": 811000,
		"v": "香港"
	}];
	areasCdn["710000"] = [{
		"k": 711000,
		"v": "台湾"
	}];
	// console.log(1, areasCdn)
	// 构造app地区接口中的对象，老版格式如下：
	/**
	 regin = {
		'130000':{
			"region_id": "130000",
			"region_name": "河北省",
			"child": {
				"130100": {
					"region_id": "130100",
					"region_name": "石家庄市",
					"child": {
						"130102": {
							"region_id": "130102",
							"region_name": "长安区"
						}
					}
				}
			}
		}
	}
	 */
	const region2 = {}
	// 省级
	areasCdn['0'].map(item => {
		if (!item.k) return;
		region2[item.k] = {}
		region2[item.k]['region_id'] = item.k
		region2[item.k]['region_name'] = item.v
		// 市级
		areasCdn[item.k] && areasCdn[item.k].map(x => {
			// 县级市级
			region2[item.k]['child'] = Object.assign({}, region2[item.k]['child'], {
				[x.k]: {
					'region_id': x.k,
					'region_name': x.v
				}
			})

			areasCdn[x.k] && areasCdn[x.k].map(a => {
				region2[item.k]['child'][x.k]['child'] = Object.assign({},
					region2[item.k]['child'][x.k]['child'], {
						[a.k]: {
							'region_id': a.k,
							'region_name': a.v
						}
					})
			})

		})
	})

	app.config.globalProperties.areas = region2
	// 地区文件是否加载完成，目前是本地文件未从远程获取，不用await
	// app.config.globalProperties.$isResolve();
}

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
const app = createSSRApp(App)
dataFn(app)

import {
	initRequest
} from './util/request/index'

export function createApp() {
	// app项目中的老的地区对象
	store.dispatch('updateareas', app.config.globalProperties.areas)
	// 新扩展的地区对象，diction中用到
	store.dispatch('updateareasnew', areasNew)

	app.use(store)
		.use(uviewPlus, () => {
			return {
				httpIns: initRequest,
				options: {
					// 修改$u.config对象的属性
					config: {
						// 修改默认单位为rpx，相当于执行 uni.$u.config.unit = 'rpx'
						unit: 'rpx'
					}
				}
			}
		});
	return {
		app
	}
}
// #endif